package com.easywan.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.common.json.JSONObject;
import com.easywan.service.IToolsChinazService;
import com.easywan.util.StringsUtils;


@Service("toolsChinazService")
public class ToolsChinazServiceImpl implements IToolsChinazService{
	private static final String SEO_URL = "http://seo.chinaz.com/";
	private static final String RANK_URL = "http://rank.chinaz.com/ajaxseo.aspx?t=rankall&on=1&type=undefined&callback=jQuery111309831664897750246_1499358199066&host=";

	public List<String> getLast(String url) {
		List<String> result = new ArrayList<String>();
		String html = null;
		try {
			html = doGet(SEO_URL+url);
		} catch (Exception e) {
			e.printStackTrace();
		}
	        Document document = Jsoup.parse(html);
	        Elements lis = document.select(".pt10 a"); 
	        for (Element a : lis) {
	        	String ip = a.attr("href");
	        	ip= ip.substring(ip.indexOf('=')+1);
	        	result.add(ip);
	        }
	        return result;

	}
	public int getRank(String url){
		String html = null;
		try {
			html = doGet(RANK_URL+url);
		} catch (Exception e) {
			e.printStackTrace();
		}
		int index = html.indexOf("br");
		if(index <= 0) return 0;
		if(html.length() <= 6) return 0;
		String rank = html.substring(index+4, index+5);
	    return Integer.valueOf(rank);
	}
	 private String doGet(String url) throws Exception {
	        CloseableHttpClient httpclient = HttpClients.createDefault();
	        HttpGet httpGet = new HttpGet(url);
	        httpGet.setHeader( "User-Agent",
	                "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");

	        CloseableHttpResponse response = null;
	        try {
	            response = httpclient.execute(httpGet);
	            if (response.getStatusLine().getStatusCode() == 200) {
	                return EntityUtils.toString(response.getEntity(), "UTF-8");
	            }
	        } finally {
	            if (response != null) {
	                response.close();
	            }
	            httpclient.close();
	        }
	        return null;
	    }
}
